<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form>
        <el-form-item>
          <el-button type="primary" icon="plus" @click="uploadFile('bisuness')">上传运营文案</el-button>
          <el-button type="primary" icon="plus" @click="showCreate">申报</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table :data="list" v-loading.body="listLoading" element-loading-text="拼命加载中" border fit
              highlight-current-row>
      <el-table-column align="center" label="序号" width="80">
        <template slot-scope="scope">
          <span v-text="getIndex(scope.$index)"> </span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="articleTitle" label="文档标题" style="width: 60px;"></el-table-column>
      <el-table-column align="center" prop="username" label="作者ID" style="width: 30px;"></el-table-column>
      <el-table-column align="center" prop="nickname" label="作者名称" style="width: 30px;"></el-table-column>
      <el-table-column align="center" prop="categoryName" label="所属类别" style="width: 10px;"></el-table-column>
      <el-table-column align="center" prop="company" label="所属公司" style="width: 30px;"></el-table-column>
      <el-table-column align="center" prop="companyCode" label="公司代码" style="width: 10px;"></el-table-column>
      <el-table-column
        align="center"
        prop="tag"
        label="文章状态"
      >
        <template slot-scope="scope">
          <el-tag
            :type="dataColorFun(stateCode[scope.row.status]) ? 'success' : 'danger'" 
            close-transition>{{stateCode[scope.row.status]}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="updateTime" label="最后更新时间" style="width: 60px;"></el-table-column>
      <el-table-column align="center" label="操作" width="100">
        <template slot-scope="scope">
          <span v-if="list[scope.$index].opt === '----'">----</span>
          <el-button 
            v-if="list[scope.$index].opt === '上传文章'"
            type="small"
            icon="edit" 
            @click="uploadFile('upload',scope.$index)"
          >上传文章</el-button>
          <el-button 
            v-if="list[scope.$index].opt === '重新上传'"
            type="small"
            icon="edit" 
            @click="uploadFile('uploadAgain',scope.$index)" 
          >重新上传</el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="remark" label="备注(原因)" style="width: 60px;"></el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page.sync="listQuery.currentPage"
      :page-size="10"
      layout="prev, pager, next, jumper"
      :total="totalCount">
    </el-pagination>
    <!-- 申报弹框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="500px">
      <el-form class="small-space" :model="tempArticle" label-position="left" label-width="60px"
               style='width: 300px; margin-left:50px;'>
        <el-form-item label="">
          <el-select v-model="applyData.categoryId" placeholder="请选择" style="width:240px;">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="">
          <el-input placeholder="请输入申报公司名称" type="text" v-model="applyData.company">
          </el-input>
        </el-form-item>
        <el-form-item label="">
          <el-input placeholder="请输入申报公司代码" type="text" v-model="applyData.companyCode">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="success" @click="confirmApply">提交申报</el-button>
      </div>
    </el-dialog>

    <!-- 填写作者信息弹框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisibleMes" width="500px">
      <el-form class="small-space" :model="tempArticle" label-position="left" label-width="60px"
               style='width: 300px; margin-left:50px;'>
        <el-form-item label="姓名" class="author-mes">
          <el-input placeholder="请输入姓名" type="text" v-model="userData.nickname">
          </el-input>
        </el-form-item>
        <el-form-item label="微信">
          <el-input placeholder="请输入微信名称" type="text" v-model="userData.wechatId">
          </el-input>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input placeholder="请输入手机号" type="text" v-model="userData.phoneNum">
          </el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input placeholder="请输入邮箱" type="text" v-model="userData.mailbox">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleMes = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="success" @click="confirmMes">确定</el-button>
      </div>
    </el-dialog>
    
    <!-- 上传文章与重新上传文章共用弹框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisibleUpload" width="500px">
      <el-form class="small-space" :model="tempArticle" label-position="left" label-width="100px"
               style='width: 350px; margin-left:50px;'>
        <el-form-item label="所属类别" class="author-mes">
          <el-input readonly="readonly" type="text" v-model="uploadBtnData.categoryName">
          </el-input>
        </el-form-item>
        <el-form-item label="标题" class="author-mes">
          <el-input :readonly="uploadFileType==='uploadAgain'?true:false" placeholder="请输入标题" type="text" v-model="uploadBtnData.articleTitle">
          </el-input>
        </el-form-item>
        <el-form-item label="所写公司名称" v-if="uploadFileType==='uploadAgain'||uploadFileType==='upload'">
          <el-input readonly="readonly" type="text" v-model="uploadBtnData.company">
          </el-input>
        </el-form-item>
        <el-form-item label="所写公司代码" v-if="uploadFileType==='uploadAgain'||uploadFileType==='upload'">
          <el-input readonly="readonly" type="text" v-model="uploadBtnData.companyCode">
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-upload
            class="upload-demo"
            :action="uploadAddress"
            :data="uploadData"
            :on-success="uploadSuccess"
            :on-error="uploadError"
            :before-upload="beforeUpload"
            :with-credentials='true'
            ref="upload"
            >
            <el-button size="small" type="primary">选择文档</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="confirmUpload">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="success" @click="confirmUpload">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import { authorState, dataColorFun } from '../../utils/state.code'
  import {Message} from 'element-ui'
  export default {
    data() {
      return {
        stateCodes: null,
        uploadBtnData:{//重新上传与上传文章弹框里面的值
          categoryName: '',
          company: '',
          companyCode: '',
          articleTitle:'',
          id:''
        },
        uploadData: {
          articleId: '',
          articleTitle: ''
        },
        stateCode: authorState,
        uploadAddress: '',//上传文章地址
        uploadFileType: '',//值为上传文章：upload或重新上传:uploadAgain,上传运营文章:uploadBisuness
        applyIng: false,//是否有文章处于申报中
        userDataModify: false,//用户是否修改信息
        userData: {//作者信息
          nickname: '',
          wechatId: '',
          phoneNum: '',
          mailbox: ''
        },
        options: [],//文章分类
        applyData: {
          categoryId: '',
          companyCode: '',
          company: ''
        },//申报提交的数据
        totalCount: 0, //分页组件--数据总条数
        list: [],//表格的数据
        listLoading: false,//数据加载等待动画
        listQuery: {
          pageNum: 1,//页码
          pageRow: 10,//每页条数
          currentPage: 1,//当前处于第几页
          name: ''
        },
        dialogStatus: 'create',
        dialogFormVisibleUpload: false,
        dialogFormVisible: false,
        dialogFormVisibleMes: false,
        textMap: {
          update: '编辑',
          create: ''
        },
        tempArticle: {
          id: "",
          content: "",
          company: ""
        },
      }
    },
    created() {
      this.getList();
      this.articleCategory()
      if(localStorage.getItem('isComplete') === 'N'){
        this.userDataModify = false
      }else if(localStorage.getItem('isComplete') === 'Y'){
        this.userDataModify = true
      }
    },
    watch: {
      'uploadBtnData.articleTitle'(val){
        this.uploadData.articleTitle = val
      }
    },
    computed: {

    },
    methods: {
      message(mes){
        //提示框
        this.$message({
          showClose: true,
          message: mes,
          type: 'success'
        });
      },
      beforeClose(done){
        // 标题不能为空
        // if(this.uploadFileType === 'upload'||this.uploadFileType === 'uploadBisuness'){
        //   if(!this.uploadBtnData.articleTitle){
        //     this.message('标题不能为空!')
        //   }else{
        //     done()
        //   }
        // }
      },
      beforeUpload(file){
        if(!this.uploadBtnData.articleTitle){
          this.message('标题不能为空!')
          return false
        }
        var testmsg=file.name.substring(file.name.lastIndexOf('.')+1)
        if(testmsg === 'doc'||testmsg=== 'docx'||testmsg==='wps'){
        }else{
          this.message('只能上传word文档或wps文档')
          return false
        }
      },
      confirmUpload(){
        // 上传文章与重新上传弹框确认按钮
        // if(this.uploadFileType === 'upload'||this.uploadFileType === 'uploadBisuness'){
        //   if(!this.uploadBtnData.articleTitle){
        //     this.message('标题不能为空!')
        //   }else{
        //     this.dialogFormVisibleUpload = false
        //   }
        // }
        this.dialogFormVisibleUpload = false
      },
      uploadFile(type,num){
        // 上传文章标题作者自己写，重新上传标题不可更改
        let domian = process.env.NODE_ENV === 'development'?'http://192.168.28.66:8080':location.origin
        this.findArticleList(this.list,num)
        if(type === "uploadAgain"){
          this.stateCodes = this.list[num].status
          this.dialogFormVisibleUpload = true
          // 重新上传
          this.uploadFileType = 'uploadAgain'
          this.uploadAddress = domian + '/article/reupload'
          this.uploadData = {
            articleId: this.uploadBtnData.id,
            code :this.stateCodes
          }
        }else if(type === "upload"){
          this.dialogFormVisibleUpload = true
          // 上传文章
          this.uploadFileType = 'upload'
          this.uploadAddress = domian + '/article/uploadDeclare'
          this.uploadData = {
            articleId: this.uploadBtnData.id,
            articleTitle: this.uploadBtnData.articleTitle
          }
          this.uploadData.articleId = this.uploadBtnData.id
          this.uploadData.articleTitle = this.uploadBtnData.articleTitle
        }else if(type === "bisuness"){
          // 上传运营文章
          // 用户是否修改信息
          if(!this.userDataModify){
            this.dialogFormVisibleMes = true
            return
          }
          this.dialogFormVisibleUpload = true
          this.uploadFileType = 'uploadBisuness'
          this.uploadBtnData.categoryName = '运营文案'
          this.uploadAddress = domian + '/article/uploadOperateArticle'
          this.uploadData = {
            categoryId: 4,
            articleTitle: this.uploadBtnData.articleTitle
          }
        }
      },
      findArticleList(list,num){
        // 从文章列表找出重新上传与上传文章的资料信息
        if(list.length>0){
          list.map((val,i)=>{
            if(num === i){
              this.uploadBtnData.categoryName = val.categoryName
              this.uploadBtnData.company = val.company
              this.uploadBtnData.companyCode = val.companyCode
              this.uploadBtnData.articleTitle = val.articleTitle
              this.uploadBtnData.id = val.id
            }
          })
        }
      },
      clearFiles(file){
        // 上传结束
        console.log(file,'file')
      },
      uploadError(){
        // 上传失败事件
        console.log('上传失败')
      },
      uploadSuccess(res, file, fileList){
        // 上传成功事件
        if(res.returnCode ==='100'){
          this.message('上传成功!')
          this.dialogFormVisibleUpload= false
          this.uploadBtnData.articleTitle = ''
          this.$refs.upload.clearFiles()
          this.getList()
        }else{
          Message({
            message: res.returnMsg,
            type: 'error',
            duration: 3 * 1000
          })
          this.$refs.upload.clearFiles()
        }
      },
      showCreate() {
        if(this.userDataModify){
          // 用户个人信息修改
          this.dialogFormVisible = true
        }else{
          //申报
          if(!this.applyIng){
            this.dialogFormVisibleMes = true
          }else{
            this.message('已有申报正在进行中!')
          }
        }
      },
      articleCategory(){
        // 获取文章分类
        this.api({
          url: "/article/category",
          method: "post",
          data: {
            categoryCode: '10001'
          }
        }).then(data => {
          if(data.list.length>0){
            data.list.map((val,i) => {
              this.options.push({
                value: val.categoryId,
                label: val.categoryName
              })
            })
          }
        })
      },
      confirmMes(){
        // 个人信息确认提交按钮
        if(!this.userData.nickname||!this.userData.wechatId||!this.userData.phoneNum||!this.userData.mailbox){
          this.message('个人信息不能为空!')
          return
        }
        this.api({
          url: "/user/update",
          method: "post",
          data: this.userData
        }).then(data => {
          this.message('用户信息修改成功!')
          this.dialogFormVisibleMes = false
          this.userData.nickname = ''
          this.userData.wechatId = ''
          this.userData.phoneNum = ''
          this.userData.mailbox = ''
          this.userDataModify = true
          localStorage.setItem('isComplete','Y')
        })
      },
      confirmApply(){
        // 提交申报
        if(!this.applyData.categoryId||!this.applyData.companyCode||!this.applyData.company){
          this.message('信息不能为空！')
          return
        }
        this.applyData.userId = 1
        this.api({
          url: "/article/declare",
          method: "post",
          data: this.applyData
        }).then(data => {
          this.getList()
          this.message('申报成功!')
          this.applyData.categoryId = ''
          this.applyData.companyCode = ''
          this.applyData.company = ''
          this.dialogFormVisible = false
        })
      },
      getList() {
        //查询列表
        this.listLoading = true;
        this.api({
          // api/article/authorListArticle?pageNum=1&pageRow=50
          url: "article/authorListArticle",
          method: "get",
          params: this.listQuery
        }).then(data => {
          this.listLoading = false;
          this.list = this.findApplyData(data.list);
          this.totalCount = data.totalCount;
        })
      },
      findApplyData(list){
        // 查找之前是否有审核中的申报,并确定操作
        if(list.length>0){
          list.map((val,i)=>{
            if(val.operation){
              let value = JSON.parse(val.operation)
              if(value[101]){
                val.opt = '重新上传'
              }else if(value[107]){
                val.opt = '----'
              }else if(value[100]){
                // 上传文章
                val.opt = '上传文章'
              }
            }
            if(val.status === "申报审核中"){
              this.applyIng = true//有处于在申报的请求
            }
          })
        }
        return list
      },
      handleSizeChange(val) {
        //改变每页数量
        this.listQuery.pageRow = val

        this.handleFilter()
      },
      handleCurrentChange(val) {
        //改变页码
        this.listQuery.pageNum = val
        this.getList();
      },
      getIndex($index) {
        //表格序号
        return (this.listQuery.pageNum - 1) * this.listQuery.pageRow + $index + 1
      },
      showUpdate($index) {
        //显示修改对话框
        this.tempArticle.id = this.list[$index].id;
        this.tempArticle.content = this.list[$index].content;
        this.dialogStatus = "update"
        this.dialogFormVisible = true
      },
      createArticle() {
        //保存新文章
        this.api({
          url: "/article/addArticle",
          method: "post",
          data: this.tempArticle
        }).then(() => {
          this.getList();
          this.dialogFormVisible = false
        })
      },
      updateArticle() {
        //修改文章
        this.api({
          url: "/article/updateArticle",
          method: "post",
          data: this.tempArticle
        }).then(() => {
          this.getList();
          this.dialogFormVisible = false
        })
      },
      filterTag(value, row) {
        return row.tag === value;
      },
      dataColorFun,
    }
  }
</script>
<style lang="stylus" scoped>

</style>

